package org.snail.department.service.impl;

import com.dingtalk.open.client.api.model.corp.Department;
import com.dingtalk.open.client.api.model.corp.DepartmentDetail;
import com.dingtalk.open.client.common.SdkInitException;
import com.dingtalk.open.client.common.ServiceException;
import com.dingtalk.open.client.common.ServiceNotExistException;
import lombok.NonNull;
import lombok.extern.log4j.Log4j;
import org.snail.common.StringUtils2;
import org.snail.common.dingding.auth.AuthHelper;
import org.snail.common.dingding.department.DepartmentHelper;
import org.snail.common.dingding.exception.OApiException;
import org.snail.department.service.manager.DeptInfoManager;
import org.snail.dept.bean.DepartDO;
import org.snail.dept.mapper.DepartmentMapper;
import org.snail.employee.service.manager.EmployeesManager;
import org.snail.exception.BaseException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
@Log4j
public class DeptInfoOptionService {

    @Autowired
    private DepartmentMapper departmentMapper ;

    @Autowired
    private DeptInfoManager deptInfoManager;

    @Autowired
    private EmployeesManager employeesManager;

    /**
     * 同步部门信息
     * @param departDO
     */
    public void synchronizeDept(DepartDO departDO ) {
        try {
            if (null == departDO) {
                log.error("执行部门任务时，部门对象为空");
            } else {
                //继续加入到队列，设置部门Manager信息
                deptInfoManager.setDeptmentManager(departDO);

                List<Department> deptChildList = getDeptChild(departDO.getId());
                for (Department department : deptChildList) {
                    DepartDO childDepartDO = new DepartDO();
                    BeanUtils.copyProperties(department, childDepartDO);

                    log.error("synchronizeDept childDepartDO: " + childDepartDO);

                    //继续加入到队列，获取部门下人员信息
                    deptInfoManager.generateChildDept(childDepartDO);

                    //继续加入到队列，设置部门Manager信息
                    deptInfoManager.setDeptmentManager(childDepartDO);

                    //更新数据，建立父子关系
                    updateDeptAndParent(childDepartDO);
                }
            }
        }  catch (Exception e) {
            log.error("钉钉接口保存至部门信息  activemq错误!", e);
        }
    }

    /**
     * 获取本部门下的子部门
     */
    private List<Department> getDeptChild(@NonNull Long id) throws BaseException, OApiException, SdkInitException, ServiceNotExistException, ServiceException {
        List<Department> departmentList = null;
        departmentList = DepartmentHelper.listDepartments(AuthHelper.getAccessToken(), id + "");
        return departmentList;
    }

    /**
     * 更新部门及父子关系
     */
    private void updateDeptAndParent(DepartDO departDO) {
        DepartDO selfDeptDB = null;
        DepartDO parentDeptDB = null;
        try{
            //从数据库获取当前对象
            if (null != departDO && null != departDO.getId()) {
                log.info("departDO.getId():" + departDO.getId() + ", departDO.getParentid():" + departDO.getParentid());
                selfDeptDB = departmentMapper.findDeptByDepartmentId(departDO.getId());
                //从数据库获取当前对象的父对象
                if (null != departDO.getParentid()) {
                    parentDeptDB = departmentMapper.findDeptByDepartmentId(departDO.getParentid());
                }
            }


            log.info("parentDeptDB: " + parentDeptDB + ", departDO : " + departDO + ", selfDeptDB : " + selfDeptDB);
            /**
             * 1、父部门没有，创建父部门
             * 2、父部门有，不变化
             */
            if (null==parentDeptDB && null!=departDO && null!=departDO.getParentid()) {
                DepartDO parentDeptDO = new DepartDO();
                parentDeptDO.setId(departDO.getParentid());
                departmentMapper.saveDeptBasicInfo(parentDeptDO);
                log.error("========================================DB:存入父部门：" + parentDeptDB);
            }

            /**
             * 1、自己有，数据库有变化，修改数据库
             * 2、自己有，数据库未存储，存入数据库
             */
            if (null != departDO && null != selfDeptDB) {//自己有
                log.info("!departDO.equals(selfDeptDB) :" + !departDO.equals(selfDeptDB) + ", departDO:" + departDO + ", selfDeptDB:" + selfDeptDB);
                if (!departDO.equals(selfDeptDB)) {    //部门信息需要修改，如果父部门有修改，同时会修改父部门关系
                    departmentMapper.updateDept(departDO);
                    log.error("===========================DB:修改群组！ 群组信息原始：" + selfDeptDB + "修改后群组信息：" + departDO);
                }
            }else if (null != departDO && null == selfDeptDB) {     //自己有，数据库没有
                departmentMapper.saveDeptBasicInfo(departDO);
                log.error("========================================DB:存入部门：" + departDO);
            }
        } catch (Exception e) {
            log.error("处理异常！异常原因：" + e, e);
            return;
        }

    }


    /**
     * 获取部门下人员信息
     * 1、更新人员信息
     * 2、保存人员和部门关系
     * @param departDO
     * @throws Exception
     */
    public void synchronizeDepatEmp(DepartDO departDO) {
        try {
            if (null == departDO || departDO.getId() < 1){
                log.error("同步部门消息的时候");
            } else {
                log.error("synchronizeDepatEmp : " + departDO);
                employeesManager.synchronizeEmployeeByDepartment(departDO);
            }
        } catch (Exception e) {
            log.error("从钉钉同步部门下人员信息出错", e);
        }
    }

    /**
     * 获取部门管理员信息
     * @param departDO
     * @throws Exception
     */
    public void synchronizeDepartManager(DepartDO departDO) {
        DepartDO selfDeptDB;
        //从数据库获取当前对象
        if (null != departDO && null != departDO.getId()) {
            selfDeptDB = departmentMapper.findDeptByDepartmentId(departDO.getId());
            try {
                if (null != selfDeptDB) {
                    DepartmentDetail departmentDetail = DepartmentHelper.getDepartmentInfo(AuthHelper.getAccessToken(), selfDeptDB.getId() + "");
                    String managers = departmentDetail.getDeptManagerUseridList();
                    if(!StringUtils2.isNull(managers)) {
                        departDO.setManagers(managers);
                        log.error("departmentDetail : " + departDO);
                        departmentMapper.updateDept(departDO);
                    }
                }
            } catch (Exception e) {
                log.error("获取部门管理员失败", e);
            }
        }
    }

}
